package com.xiaolin.token.interceptor;

import com.xiaolin.token.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginInterceptor
 * @Description 请求拦截器
 * @Detail detail
 * @Author MyPC
 * @Date 2020/10/7
 * @Version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //String token = request.getHeader("Authorization");
        boolean flag=false;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if("token".equals(cookie.getName())){
                String token=cookie.getValue();
                if(!StringUtils.isEmpty(token)){
                    flag=TokenUtils.verify(token);
                }
            }
        }
        if(flag){
           return true;
        }else {
            try {
                response.sendRedirect(request.getContextPath()+"/login-token.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
